package com.ultrapower.ctool.xn_app;

import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ultrapower.ctool.ConfUtils;
import com.ultrapower.ctool.bean.WangGeBean;
import com.ultrapower.ctool.core.CustomApplication;
import com.ultrapower.ctool.core.JywgAutoCompleteAdater;
import com.ultrapower.ctool.http.BaseActivity;
import com.ultrapower.ctool.model.RegisterRolePirVO;
import com.ultrapower.ctool.utils.InstanceUtil;
import com.ultrapower.ctool.utils.JydwHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ChangeWangGeActivity extends BaseActivity implements View.OnClickListener {
    private EditText sid_change_wg;//编号
    //private TextView stype_change_wg;//事件类型
    private Spinner stype_change_wg_sp;//事件类型下拉框
    //private TextView step_change_wg;//事件步骤
    private Spinner step_change_wg_sp;//事件步骤下拉框
    private EditText dwid_chaneg_wg;//单位(数字)
    private EditText sname_change_wg;//事件名
    private EditText sAddress_change_wg;//事件发生地址
    private EditText trTableid_change_wg;//关联的巡查表编号
    private TextView save_change_wg;
    private TextView cancle_change_wg;
    private static final List<RegisterRolePirVO> stypes = new ArrayList<RegisterRolePirVO>();
    private static final List<RegisterRolePirVO> steps = new ArrayList<RegisterRolePirVO>();
    private Map<String, EditText> textMap = new HashMap<String, EditText>();
    private Map<String, Spinner> spinnerMap = new HashMap<String, Spinner>();
    private Map<String, Map<String, Object>> resultMap;
    // private ArrayAdapter<String> stypeAdapter;
    // private ArrayAdapter<String> stepAdapter;
    private CustomApplication application;
    //private JywgAutoCompleteAdater cursorAdapter;
    //private OkHttpClient client = new OkHttpClient();
    private Gson gson = new Gson();
    private AdapterView.OnItemSelectedListener OnCatSpinnerCL = new AdapterView.OnItemSelectedListener() {
        public void onItemSelected(AdapterView<?> parent, View view, int pos,
                                   long id) {
            ((TextView) parent.getChildAt(0)).setTextColor(Color.BLACK);
            ((TextView) parent.getChildAt(0)).setTextSize(18);
        }

        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(ChangeWangGeActivity.this, WangGeActivity.class);

                    startActivity(intent);
                    finish();
                    break;
                case 0:
                    Toast.makeText(getApplicationContext(), "系统出现异常", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
    static {
        steps.add(new RegisterRolePirVO("0", ""));
        steps.add(new RegisterRolePirVO("1", "保存事件"));
        steps.add(new RegisterRolePirVO("2", "处理事件"));
        steps.add(new RegisterRolePirVO("3", "验收事件"));
        stypes.add(new RegisterRolePirVO("0", ""));
        stypes.add(new RegisterRolePirVO("1", "一般隐患"));
        stypes.add(new RegisterRolePirVO("2", "重大隐患"));
        stypes.add(new RegisterRolePirVO("3", "违法生产经营行为"));
        stypes.add(new RegisterRolePirVO("4", "其他安全生产"));

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_wang_ge);
        init();
        //根据ID查询后台数据
        Intent intent = getIntent();
        //initData(intent.getStringExtra("sid"));
        getWangGeInfo(intent.getStringExtra("sid"));
    }

    private void init() {
        sid_change_wg = (EditText) findViewById(R.id.sid_change_wg);
        textMap.put("sid", sid_change_wg);
        //stype_change_wg = (TextView)findViewById(R.id.stype_change_wg);
        stype_change_wg_sp = (Spinner) findViewById(R.id.stype_change_wg_sp);
        spinnerMap.put("stype", stype_change_wg_sp);
        //step_change_wg = (Spinner)findViewById(R.id.step_change_wg);
        step_change_wg_sp = (Spinner) findViewById(R.id.step_change_wg_sp);
        spinnerMap.put("step", step_change_wg_sp);
        dwid_chaneg_wg = (EditText) findViewById(R.id.dwid_chaneg_wg);
        textMap.put("dwid", dwid_chaneg_wg);
        sname_change_wg = (EditText) findViewById(R.id.sname_change_wg);
        textMap.put("sname", sname_change_wg);
        sAddress_change_wg = (EditText) findViewById(R.id.sAddress_change_wg);
        textMap.put("saddress", sAddress_change_wg);
        trTableid_change_wg = (EditText) findViewById(R.id.trTableid_change_wg);
        textMap.put("trtableid", trTableid_change_wg);
        save_change_wg = (TextView) findViewById(R.id.save_change_wg);
        cancle_change_wg = (TextView) findViewById(R.id.cancle_change_wg);
        application = (CustomApplication) getApplication();

        save_change_wg.setOnClickListener(this);
        cancle_change_wg.setOnClickListener(this);



        /*
        save_change_wg.setOnClickListener(this);
        cancle_change_wg.setOnClickListener(this);

        //将可选内容与ArrayAdapter连接起来
        stypeAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,stypes);
        //设置下拉列表的风格
        stypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        stype_change_wg_sp.setAdapter(stypeAdapter);
        //添加事件Spinner事件监听
        stype_change_wg_sp.setOnItemSelectedListener(new ChangeWangGeActivity.StypeSpinnerSelectedListener());
        //设置默认值
        stype_change_wg_sp.setVisibility(View.VISIBLE);

        //将可选内容与ArrayAdapter连接起来
        stepAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,steps);
        //设置下拉列表的风格
        stepAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //将adapter 添加到spinner中
        step_change_wg_sp.setAdapter(stepAdapter);
        //添加事件Spinner事件监听
        step_change_wg_sp.setOnItemSelectedListener(new ChangeWangGeActivity.StepSpinnerSelectedListener());
        //设置默认值
        step_change_wg_sp.setVisibility(View.VISIBLE);
        */
    }

    /*
        //使用数组形式操作
        class StypeSpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                       long arg3) {
                stype_change_wg.setText(stypes[arg2]);
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        }

        //使用数组形式操作
        class StepSpinnerSelectedListener implements AdapterView.OnItemSelectedListener {

            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
                                       long arg3) {
                step_change_wg.setText(steps[arg2]);
            }

            public void onNothingSelected(AdapterView<?> arg0) {
            }
        }
    */
    private void getWangGeInfo(final String sid) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                Request request=null;
                try {
                    OkHttpClient client = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("userId", String.valueOf(application.getLoginUser().getLogin_id()))
                            .build();
                    request = new Request.Builder().url(ConfUtils.SERVICE_URL + "grid_event/update/c_aj_wgsj-" + sid).post(requestBody).build();
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {//成功
                        String result = response.body().string();
                        resultMap = gson.fromJson(result, Map.class);
                        System.out.println(resultMap);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                for (final Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (textMap.get(entry.getKey()) != null) {
                                        textMap.get(entry.getKey()).setText(entry.getValue().toString());
                                        textMap.get(entry.getKey()).setEnabled ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                        textMap.get(entry.getKey()).setFocusable ((Boolean) resultMap.get("result").get(entry.getKey()+"_qx"));
                                    } else {
                                        if (entry.getKey().endsWith("_List") && entry.getValue() instanceof List) {
                                            List<Map<String, Object>> list = (List<Map<String, Object>>) entry.getValue();
                                            List<RegisterRolePirVO> voList = new ArrayList<RegisterRolePirVO>();
                                            for (Map<String, Object> value : list) {
                                                try {
                                                    value.put("id", String.valueOf(value.get("id")).split("\\.").length == 1 ? String.valueOf(value.get("id")) : String.valueOf(value.get("id")).split("\\.")[0]);
                                                    RegisterRolePirVO vo = (RegisterRolePirVO) InstanceUtil.mapToObject(value, RegisterRolePirVO.class);
                                                    voList.add(vo);
                                                } catch (Exception e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                            final Spinner spinner = spinnerMap.get(entry.getKey().split("_List")[0]);
                                            final ArrayAdapter<RegisterRolePirVO> aradapter = new ArrayAdapter<RegisterRolePirVO>(getApplicationContext(), android.R.layout.simple_spinner_item, voList);
                                            aradapter.setDropDownViewResource(R.layout.simple_dropdown_item_1line);
                                            spinner.setAdapter(aradapter);
                                            final int k = aradapter.getCount();
                                            //System.out.println(aradapter.getItem(1).getId().toString());
                                            spinner.setOnItemSelectedListener(OnCatSpinnerCL);
                                            for (int i = 0; i < k; i++) {
                                                if (resultMap.get("result").get(entry.getKey().split("_List")[0]).equals(aradapter.getItem(i).getId().toString())) {
                                                    spinner.setSelection(i);
                                                    break;
                                                }
                                            }

                                        }
                                    }
                                }
                                for(Map.Entry<String, Spinner> entry1 : spinnerMap.entrySet()){
                                    entry1.getValue().setEnabled ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                                    entry1.getValue().setFocusable ((Boolean) resultMap.get("result").get(entry1.getKey()+"_qx"));
                                }
                            }
                        });

                    }else {
                        Message message = new Message();
                        message.what = 0;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                } finally {
                    if(response!=null)response.close();

                }
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.save_change_wg:
                if ("".equals(((RegisterRolePirVO) stype_change_wg_sp.getSelectedItem()).getId())
                        || "".equals(((RegisterRolePirVO) step_change_wg_sp.getSelectedItem()).getId())
                        || "".equals(dwid_chaneg_wg.getText().toString().trim()) // "".equals(((RegisterRolePirVO) dwid_chaneg_wg_sp.getSelectedItem()).getId())
                        || "".equals(sname_change_wg.getText().toString().trim())
                        || "".equals(sAddress_change_wg.getText().toString().trim())
                        || "".equals(trTableid_change_wg.getText().toString().trim())
                        ) {
                    Toast.makeText(getApplicationContext(), "请填写完整信息", Toast.LENGTH_SHORT).show();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Response response = null;
                            try {
                                OkHttpClient client = new OkHttpClient();
                                //String _id = new DBHelper(changVo).queryBycn(entry.getValue().getText().toString());
                                FormBody.Builder builder = new FormBody.Builder()
                                        .add("userId", String.valueOf(application.getLoginUser().getLogin_id()));
                                for (Map.Entry<String, EditText> entry : textMap.entrySet()) {

                                        resultMap.get("result").put(entry.getKey(), entry.getValue().getText().toString());

                                }
                                for (Map.Entry<String, Spinner> entry : spinnerMap.entrySet()) {
                                    resultMap.get("result").put(entry.getKey().split("_List")[0], ((RegisterRolePirVO) entry.getValue().getSelectedItem()).getId());
                                }
                                for (Map.Entry<String, Object> entry : resultMap.get("result").entrySet()) {
                                    if (entry.getValue() instanceof String) {
                                        builder.add(entry.getKey(), (String) entry.getValue());
                                    }
                                }
                                RequestBody requestBody = builder.build();
                                Request request = new Request.Builder().url(ConfUtils.SERVICE_URL + "form/doUpdate/c_aj_wgsj").post(requestBody).build();
                                response = client.newCall(request).execute();
                                if (response.isSuccessful()) {//成功
                                    String result = response.body().string();
                                    System.out.println("result:" + result);
                                    Map<String, Object> resultMap = gson.fromJson(result, Map.class);
                                    if ((boolean) resultMap.get("success")) {
                                        Message message = new Message();
                                        message.what = 1;
                                        handler.sendMessage(message);
                                    }
                                } else {
                                    Message message = new Message();
                                    message.what = 0;
                                    handler.sendMessage(message);
                                }
                            } catch (Exception e) {
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            } finally {
                                if (response != null) response.close();

                            }
                        }
                    }).start();
                    Toast.makeText(getApplicationContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    Intent intent2 = new Intent(ChangeWangGeActivity.this, WangGeActivity.class);
                    startActivity(intent2);
                    finish();
                }

                break;
            case R.id.cancle_change_wg:
//                Intent intent2 = new Intent(ChangeWangGeActivity.this, WangGeActivity.class);
//                startActivity(intent2);
                finish();
                break;
        }
    }

}

